;$(function () {

    appendImg();

    function appendImgByArea(areaId, $tr) {
        var attachUrl = basePath + "/attachment";
        var baseDownloadUrl = baseDomain + "/attachment/";
        $.ajax({
            url: attachUrl + "/getAttachmentsByBoxId.json?areaId=" + areaId,
            type: "get",
            dataType: "json",
            success: function (r) {
                for (var key = 0; key < r.length; key++) {
                    var val = r[key];
                    var html =
                        '<div><hr><img alt="" src="' + baseDownloadUrl + val.downloadUrl + '">' +
                        '<a href="javascript:void(0);" data-id="' + val.attachmentId + '" class="download-a" title="' + val.fileName + '" style="display:inline-block;padding: 3px;background-color: #FFE7B7;color: #444;margin:2px;">' + val.fileName + '</a>' +
                        '</div>';
                    $tr.append(html);
                }
            }
        });
    }

    function appendImg() {
        var quesId = $("input[name='question.id']").val();

        var areaId = quesId + "-QUESTION";
        var $tr = $(".question");
        appendImgByArea(areaId, $tr);

        var areaId = quesId + "-ANALYSIS";
        var $tr = $(".analysis");
        appendImgByArea(areaId, $tr);
    }

    $(".form-table").on("click", ".download-a", function () {
        var attachmentId = $(this).data("id");
        downloadImg(attachmentId);
    });

    function downloadImg(attachmentId) {
        var url = basePath + "/attachment/download.json?address=" + attachmentId;
        var downloadIframe = document.getElementById('downLoadIframe');
        if (downloadIframe) {
            downloadIframe.src = url;
        } else {
            downloadIframe = document.createElement('iframe');
            downloadIframe.id = 'downLoadIframe';
            downloadIframe.src = url;
            downloadIframe.style.display = "none";
            document.body.appendChild(downloadIframe);
        }
    }
});